package com.zdp.usercenter.rocketmq;

import com.zdp.usercenter.dao.user.BonusEventLogMapper;
import com.zdp.usercenter.dao.user.UserMapper;
import com.zdp.usercenter.domain.dto.message.UserAddBonusMsgDTO;
import com.zdp.usercenter.domain.entity.user.BonusEventLog;
import com.zdp.usercenter.domain.entity.user.User;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author sesshomaru
 * @date 2020/9/22 20:11
 *
 * 消费内容中心审核成功时发送的用户加积分消息
 */
                                                                 //这里的泛型写消息体
@Service
@Slf4j
// 这里就有区别了生成者的group是写在yml里面的 而这里的消费者的group是写在注解上的
@RocketMQMessageListener(consumerGroup = "consumer-group", topic = "add-bonus")
@RequiredArgsConstructor(onConstructor = @_(@Autowired))
public class AddBonusRocketMqListener implements RocketMQListener<UserAddBonusMsgDTO> {
    private final UserMapper userMapper;

    private final BonusEventLogMapper bonusEventLogMapper;

    @Override
    public void onMessage(UserAddBonusMsgDTO message) {
        // 当收到消息的时候，执行的业务
        // 1. 为用户加积分
        Integer userId = message.getUserId();
        User user = this.userMapper.selectByPrimaryKey(userId);
        Integer bonus = message.getBonus();
        // 新增积分
        user.setBonus(user.getBonus() + message.getBonus());
        this.userMapper.updateByPrimaryKeySelective(user);
        // 2. 记录日志到bonus_event_log表
        this.bonusEventLogMapper.insert(
                BonusEventLog.builder()
                .userId(userId)
                .value(bonus)
                .event("投稿事件")
                .createTime(new Date())
                .description("投稿加积分...")
                .build()
        );
        log.info("积分添加完毕...");
    }
}
